package com.wisezone.net.ex05_server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务端程序
 */
public class Server {
    private static final int PORT = 9527;
    public List<Socket> socketLists = new ArrayList<>();

    public void startServer() {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("启动服务端...");
            while (true) {
                Socket socket = serverSocket.accept(); //监听客户端socket连接
                System.out.println(socket.getInetAddress() + " 登录成功");
                socketLists.add(socket); //添加当前socket到集合
                new ClientReceiveMsgThread(socket); //每来一个客户端都会创建一个线程，接收该客户端发送的消息

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 接收客户端消息的线程
     */
    class ClientReceiveMsgThread implements Runnable {
        private Socket socket;

        public ClientReceiveMsgThread(Socket socket) {
            this.socket = socket;
            new Thread(this).start();
        }

        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (true) {
                    String message = br.readLine();
                    if (message != null) {
                        System.out.println(socket.getInetAddress() + ": " + message);
                        changeSendMessage(socket,message); //接收到消息转到给所有其它客户端
                    }
                }
            } catch (IOException e) {
//                e.printStackTrace();
            }
        }
    }

    /**
     * 转发消息
     */
    public void changeSendMessage(Socket currentSocket,String message) {
        try {
            for (Socket socket : socketLists) {
                if(currentSocket == socket){
                    continue;
                }
                PrintWriter pw = new PrintWriter(socket.getOutputStream());
                pw.println(message);
                pw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
